package com.acme.chat.client;

import java.util.ArrayList;
import java.util.List;

import com.acme.chat.message.Message;
import com.acme.chat.server.Server;

public class ClientImpl implements ChatClient {

    protected Server server;
    protected String name;
    protected String room;
    protected List<ClientListener> listeners;

    public ClientImpl(String name, final String room) {

        if (name == null) {
            name = ChatClient.DEFAULT_NAME;
        }

        this.name = name;
        this.room = room;
        listeners = new ArrayList<ClientListener>();
    }

    public String getRoom() {
        return room;
    }

    public String getName() {
        return name;
    }

    public void connect(Server server) {
        if (!isConnected()) {
            if (server.addClient(this)) {
                this.server = server;
            }
        }
    }

    public void disconnect() {
        if (isConnected()) {
            server.removeClient(this);
            server = null;
            callListenersOnDisconnect();
        }
    }

    public boolean isConnected() {
        return server != null;
    }

    public boolean sendMessage(Message message) {
        if (isConnected()) {
            server.processMessage(message, this);
            return true;
        }
        return false;
    }

    public void incomingMessage(Message message) {
        callListenersOnGetMessage(message);
    }


    private void callListenersOnDisconnect() {
        for (ClientListener listener : listeners) {
            listener.onDisconnect();
        }
    }

    private void callListenersOnGetMessage(Message message) {
        for (ClientListener listener : listeners) {
            listener.onGetMessage(message);
        }
    }

    public void addListener(ClientListener listener) {
        listeners.add(listener);
    }

}
